package server;

import java.io.InputStream;
import java.net.Socket;
import java.util.List;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;
    private Map<String,HttpServlet> servletMap;
    private MiniMapper mapper;

    public RequestProcessor(Socket socket, Map<String, HttpServlet> servletMap, MiniMapper mapper) {
        this.socket = socket;
        this.servletMap = servletMap;
        this.mapper = mapper;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
            if (request.getUrl().contains("demo")) {
                List<MiniHost> hostList = mapper.getHosts();
                for (MiniHost host : hostList) {
                    for(MiniContext context:host.getMiniContexts()){
                        List<MiniWrapper> wrapperList = context.getMiniWrappers();
                        for(MiniWrapper miniWrapper:wrapperList){
                            Map<String, HttpServlet> httpServlet = miniWrapper.getMapperServlet();
                            HttpServlet servletInfo = httpServlet.get(request.getUrl());
                            if (servletInfo != null){
                                servletInfo.service(request,response);
                            }
                        }
                    }
                }
            }
            // 静态资源处理
            else if(servletMap.get(request.getUrl()) == null) {
                response.outputHtml(request.getUrl());
            }else{
                // 动态资源servlet请求
                HttpServlet httpServlet = servletMap.get(request.getUrl());
                httpServlet.service(request,response);
            }
            socket.close();
        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}
